<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">景点名称</label>
        <el-input v-model="query.scenicName" clearable placeholder="景点名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">省</label>
        <el-input v-model="query.province" clearable placeholder="省" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">市</label>
        <el-input v-model="query.city" clearable placeholder="市" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">是否已游玩</label>
        <el-input v-model="query.isFlag" clearable style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="800px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="138px">
          <el-form-item label="景点名称">
            <el-input v-model="form.scenicName" style="width: 300px;" />
          </el-form-item>
          <el-form-item label="省">
            <el-input v-model="form.province" style="width: 300px;" />
          </el-form-item>
          <el-form-item label="市">
            <el-input v-model="form.city" style="width: 300px;" />
          </el-form-item>
          <el-form-item label="县">
            <el-input v-model="form.town" style="width: 300px;" />
          </el-form-item>
          <el-form-item label="坐标">
            <el-input v-model.trim="form.gisx" style="width: 150px;" :readonly="true" />
            <el-input v-model.trim="form.gisy" style="width: 150px;" :readonly="true" />
            <el-button :loading="crud.cu === 2" type="primary" @click="getPoint">定位</el-button>
          </el-form-item>
          <el-form-item label="攻略">
            <el-input v-model="form.remark" type="textarea" style="width: 300px;" />
          </el-form-item>
          <el-form-item label="路线">
            <el-input v-model="form.route" type="textarea" style="width: 300px;" />
          </el-form-item>
          <el-form-item label="景区价格">
            <el-input v-model="form.scenicPrice" style="width: 300px;" />
          </el-form-item>
          <el-form-item label="图片" style="width: 800px;">
            <el-upload
              :action="imagesUploadApi + '?name=' + form.picName"
              list-type="picture-card"
              :limit="10"
              :on-exceed="handleExceed"
              :on-success="handleSuccess"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :before-upload="onBeforeUpload"
              :headers="headers"
              :file-list="form.pictureList"
              accept="image/jpeg,image/jpg,image/png"
            >
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item>
          <el-form-item label="是否游玩">
            <el-input v-model="form.isFlag" style="width: 300px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="scenicName" label="景点名称" align="center" />
        <el-table-column prop="province" label="省" align="center" width="80" />
        <el-table-column prop="city" label="市" align="center" width="80" />
        <el-table-column prop="town" label="县" align="center" width="80" />
        <el-table-column prop="remark" label="攻略" align="center" show-overflow-tooltip />
        <el-table-column prop="route" label="路线" align="center" show-overflow-tooltip />
        <el-table-column prop="scenicPrice" label="景区价格" align="center" width="80" />

        <el-table-column prop="picPath" label="图片路径" align="center">

          <template slot-scope="scope">
            <el-image
              style="width: 100px; height: 100px"
              :src="getUrl(scope.row.picPath)"
              :preview-src-list="getSrcList(scope.row.picPath)"
            />
          </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','scenic:edit','scenic:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
      <BaiduMap ref="baiduMap" @change="returnPoint" />
    </div>
  </div>
</template>

<script>
import BaiduMap from '@/views/components/BaiduMap'
import crudScenic from '@/api/scenic'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'

const defaultForm = { pictureList: [], id: null, scenicName: null, gisx: null, gisy: null, province: null, city: null, town: null, remark: null, route: null, scenicPrice: null, picPath: null, isFlag: null }
export default {
  name: 'Scenic',
  components: { BaiduMap, pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: 'scenic', url: 'api/scenic', idField: 'id', sort: 'id,desc', crudMethod: { ...crudScenic }})
  },
  data() {
    return {
      headers: { 'Authorization': getToken() },
      permission: {
        add: ['admin', 'scenic:add'],
        edit: ['admin', 'scenic:edit'],
        del: ['admin', 'scenic:del']
      },
      rules: {
      },
      queryTypeOptions: [
        { key: 'scenicName', display_name: '景点名称' },
        { key: 'province', display_name: '省' },
        { key: 'city', display_name: '市' },
        { key: 'town', display_name: '县' }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'imagesUploadApi'
    ])
  },
  methods: {
    getUrl(row) {
      if (row) {
        var str = row.substr(0, row.length - 1).split('|')
        return this.baseApi + str[0]
      } else {
        return null
      }
    },
    getSrcList(row) {
      if (row) {
        var str = row.substr(0, row.length - 1).split('|')
        var arr = []
        for (var i = 0; i <= str.length; i++) {
          arr.push(this.baseApi + str[i])
        }
        return arr
      } else {
        return null
      }
    },
    [CRUD.HOOK.afterToCU](crud, form) {
      if (this.form.picPath) {
        var arr = this.form.picPath.split('|')
        for (var i = 0; i < arr.length; i++) {
          if (arr[i]) {
            var array = arr[i].split('/')
            this.form.pictureList.push({
              'url': this.baseApi + arr[i],
              response: { 'realName': array[3], 'type': array[2] }
            })
          }
        }
      }
    },
    handleSuccess(response, file, fileList) {
      console.log(file)
      this.form.picPath = ''
      for (var i = 0; i < fileList.length; i++) {
        this.form.picPath += '/file/' + fileList[i].response.type + '/' + fileList[i].response.realName + '|'
      }
    },
    // 图片上传超出最大数量
    handleExceed(file, fileList) {
      this.$message({
        message: '每条最多上传十张图片',
        center: true,
        type: 'warning'
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file, fileList) {
      this.form.picPath = ''
      for (var i = 0; i < fileList.length; i++) {
        this.form.picPath += '/file/' + fileList[i].response.type + '/' + fileList[i].response.realName + '|'
      }
    },
    onBeforeUpload(file) {
      const isIMAGE = (file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png')
      const isLt1M = file.size / 1024 / 1024 < 100

      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.form.picName = file.name
      return isIMAGE && isLt1M
    },
    handlePreview(file) {
      var a = this.$refs['downloadA']
      a.href = this.baseApi + '/file/' + file.response.type + '/' + file.response.realName
      a.click()
    },
    returnPoint(point) {
      this.form.gisx = point.lng.toFixed(5)
      this.form.gisy = point.lat.toFixed(5)
    },
    getPoint() {
      this.$refs.baiduMap.gisX = this.form.gisx
      this.$refs.baiduMap.gisY = this.form.gisy
      this.$refs.baiduMap.dialog = true
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.beforeToEdit]() {
      this.$refs.baiduMap.gisX = this.form.gisx
      this.$refs.baiduMap.gisY = this.form.gisy
      setTimeout(() => {
        this.$refs.baiduMap.addPoint()
      }, 1000)

      return true
    }

  }
}
</script>

<style scoped>

</style>
